package cn.db101.api.complex.service.weather

import cn.db101.api.complex.api.weather.WeatherPropertiesConfig
import cn.db101.api.complex.api.weather.xinzhi.XinZhiClient
import cn.db101.api.complex.component.Slf4j.Companion.log
import cn.db101.api.complex.component.WeatherMapper
import cn.db101.api.complex.model.request.WeatherCurrentRequest
import cn.db101.api.complex.model.request.WeatherFutureRequest
import cn.db101.api.complex.model.response.WeatherCurrentResponse
import cn.db101.api.complex.model.response.WeatherFutureResponse
import com.alibaba.csp.sentinel.SphU
import com.alibaba.csp.sentinel.slots.block.BlockException
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

/**
 * @author zooy
 * @since 2024/11/18-16:33
 */
@Component
class XinZhiWeather: ThirdWeather {

    @Autowired
    private lateinit var xinZhiClient: XinZhiClient

    @Autowired
    private lateinit var weatherPropertiesConfig: WeatherPropertiesConfig

    override fun futureWeather(weatherFutureRequest: WeatherFutureRequest): WeatherFutureResponse? {
        try {
            SphU.entry("xinZhiWeather").use {
                val futureResponse = xinZhiClient.queryFutureWeather(weatherPropertiesConfig.xinZhi?.key, weatherFutureRequest.city)
                return WeatherMapper.INSTANCE.xinZhiFutureConvert(futureResponse?.results?.first())
            }
        } catch(be: BlockException) {
            log.info("BlockException")
        }

        return null
    }

    override fun currentWeather(weatherCurrentRequest: WeatherCurrentRequest): WeatherCurrentResponse? {

        try {
            SphU.entry("xinZhiWeather").use {
                val currentWeather =
                    xinZhiClient.queryCurrentWeather(weatherPropertiesConfig.xinZhi?.key, weatherCurrentRequest.city)
                return WeatherMapper.INSTANCE.xinZhiCurrentConvert(currentWeather?.results?.first()?.now)
            }
        } catch(be: BlockException) {
            log.info("BlockException")
        }

        return null
    }
}
